<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport"
        content="width=device-width, initial-scale=1 minimum-scale=1 maximum-scale=1 user-scalable=no"/>
  <script src="./assets/js/jquery/jquery.min.js"></script>
  <script src="./assets/js/jquery/jquery.serializejson.min.js"></script>
  <link rel="stylesheet" href="./assets/css/style.css" type="text/css"/>
  <title>统一认证平台</title>
</head>

<body>
<div class="bottom-container">
</div>

<div id="error_box">
</div>
<div class="form-container">

  <form class="form-signin" method="post"  id="forget_from" action="##"  onsubmit="return false">
    <input type="hidden" id="captchaId" name="captchaId" value=""/>
    <input type="hidden" id="loginType" name="loginType" value="passwordLogin"/>

    <div class="welcome-text">
      <img src="./assets/img/logo.png" alt="logo" width="60">
      <span>
                    统一认证平台
                </span>
    </div>
    <div>
      <input type="text" id="phone" name="phone" class="form-control" placeholder="手机号" autofocus
             onblur="verifyPhone(id)"/>
    </div>
    <div id="passContainer">
      <input type="password" id="password" name="password" class="form-control" placeholder="请输入密码"
             onblur="verifyPassword(id)"/>
    </div>
    <div id="confirmPasswordContainer">
      <input type="password" id="confirmPassword" name="confirmPassword" class="form-control" placeholder="确认密码"
             onblur="verifyConfirmPassword(id)"/>
    </div>
    <div  class="code-container" id="smsContainer">
      <input type="text" name="code" class="form-control" placeholder="请输入验证码" onblur="leave()">
      <a id="getSmsCaptchaBtn" class="btn btn-light btn-block bg-white getCaptcha" href="javascript:getSmsCaptcha()">获取验证码</a>
    </div>
    <button class="btn btn-lg btn-primary btn-block"  id="forget_submit" type="submit" onclick="forget()" >提&nbsp;&nbsp;&nbsp;&nbsp;交</button>
  </form>
</div>
</body>
</html>


<script>

  function forget() {
    document.getElementById("forget_submit").setAttribute("class",null)
    document.getElementById("forget_submit").disabled = true;
    let requestOptions = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify($('#forget_from').serializeJSON()),
      redirect: 'follow'
    };
    fetch(`${window.location.origin}/forget`, requestOptions)
            .then(response => response.text())
            .then(r => {
              if (r) {
                let result = JSON.parse(r);
                if (result.code === 200) {
                  showError(result.message)
                  setTimeout(toLogin, 2000)
                  //sleep(3000);
                } else {
                  showError(result.message)
                  setTimeout(toForget, 1000)
                }
              }
            })
            .catch(error => console.log('error', error));
  }

  function toLogin() {
    window.location.href = document.referrer;
  }

  function toForget() {
  }

  function leave() {
    document.body.scrollTop = document.documentElement.scrollTop = 0;
  }

  const ids = ['phone','password','confirmPassword'];

  function check(id,verify,msg) {
    if (verify) {
      showError(msg)
      let number = ids.indexOf(id)
      let sliceIds = ids.slice(number+1,ids.length);
      for (let id of sliceIds) {
        document.getElementById(id).setAttribute("class",null)
        document.getElementById(id).disabled = true;
      }
      document.getElementById("forget_submit").setAttribute("class",null)
      document.getElementById("forget_submit").disabled = true;
    } else {
      let number = ids.indexOf(id)
      let sliceIds = ids.slice(number+1,ids.length);
      for (let id of sliceIds) {
        document.getElementById(id).disabled = false;
      }
      document.getElementById("forget_submit").setAttribute("class","btn btn-lg btn-primary btn-block")
      document.getElementById("forget_submit").disabled = false;
    }
  }

  function verifyPhone(id) {
    let phone = document.getElementById('phone').value;
    const regex = /^(13[0-9]|14[5-9]|15[0-3,5-9]|166|17[0-8]|18[0-9]|19[0-3,5-9])\d{8}$/;
    let verify = (!regex.test(phone));
    let msg ="手机号格式错误.";
    check(id,verify,msg);
  }

  function verifyPassword(id) {
    let password = document.getElementById('password').value;
    const regex = /^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9]+/;
    let msg ="密码必须由字母和数字组成.";
    let verify = (!regex.test(password));
    check(id,verify,msg);
  }

  function verifyConfirmPassword(id) {
    let password = document.getElementById('password').value;
    let confirmPassword = document.getElementById('confirmPassword').value;
    let verify = (password !== confirmPassword);
    let msg ="两次密码不一致.";
    check(id,verify,msg);
  }


  function getSmsCaptcha() {

    let phone = document.getElementById('phone').value;
    if (phone === null || phone === '' || typeof phone === 'undefined') {
      showError('手机号码不能为空.')
      return;
    }

    // 禁用按钮
    let getSmsCaptchaBtn = document.getElementById('getSmsCaptchaBtn');
    getSmsCaptchaBtn.style.pointerEvents = 'none';
    // 开始1分钟倒计时
    resetBtn(getSmsCaptchaBtn);

    let requestOptions = {
      method: 'GET',
      redirect: 'follow'
    };

    fetch(`${window.location.origin}/getSmsCaptcha?phone=${phone}&type=forget`, requestOptions)
            .then(response => response.text())
            .then(r => {
              if (r) {
                let result = JSON.parse(r);
                if (!result.success) {
                    showError('获取验证码失败：' + result.message)
                }
              }
            })
            .catch(error => console.log('error', error));
  }

  /**
   * 1分钟倒计时
   */
  function resetBtn(getSmsCaptchaBtn) {
    let s = 60;
    getSmsCaptchaBtn.innerText = `重新获取(${--s})`
    // 定时器 每隔一秒变化一次（1000ms = 1s）
    let t = setInterval(() => {
      getSmsCaptchaBtn.innerText = `重新获取(${--s})`
      if (s === 0) {
        clearInterval(t)
        getSmsCaptchaBtn.innerText = '获取验证码'
        getSmsCaptchaBtn.style.pointerEvents = '';
      }
    }, 1000);

  }

  getVerifyCode();
</script>
<script th:inline="javascript">

  function showError(message) {
    let errorBox = document.getElementById("error_box");
    errorBox.innerHTML = message;
    errorBox.style.display = "block";
    setTimeout(() => {
      closeError();
    }, 3000)
  }

  function closeError() {
    let errorBox = document.getElementById("error_box");
    errorBox.style.display = "none";
  }

  let error = [[${ error }]]
  if (error) {
    if (window.Notification) {
      Notification.requestPermission(function () {
        if (Notification.permission === 'granted') {
          // 用户点击了允许
          let n = new Notification('登录失败', {
            body: error,
            icon: './assets/img/logo.png'
          })

          setTimeout(() => {
            n.close();
          }, 3000)
        } else {
          showError(error);
        }
      })
    }
  }
</script>
